package com.atu.atugra.tools;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
/**
 * @Author Chen Huan Ke
 * @Date 2024/7/18 10:18
 * @Version 1.0
 */
@Component
public class JwtUtil {


    // 有效期
    private static final long JWT_EXPIRE = 24 * 24 * 60 * 60 * 1000L;  //24天
    // 令牌秘钥
    private static final String JWT_KEY = "w4IsxlHEV5rjnPZjGD7pIZLgc5ZcW5Bb";
    //token过期多久可以继续刷新
    private static final long Refresh_Token_Time = 24 * 24 * 60 * 60; //1天 已转化

    public static String createToken(Object data) {
        // 当前时间
        long currentTime = System.currentTimeMillis();
        // 过期时间
        long expTime = currentTime + JWT_EXPIRE;
        // 构建jwt
        JwtBuilder builder = Jwts.builder()
                .setId(UUID.randomUUID() + "")
                .setSubject(JSON.toJSONString(data))
                .setIssuer("system")
                .setIssuedAt(new Date(currentTime))
                .signWith(SignatureAlgorithm.HS256, encodeSecret(JWT_KEY))
                .setExpiration(new Date(expTime));
        return builder.compact();
    }

    private static SecretKey encodeSecret(String key) {
        byte[] encode = Base64.getEncoder().encode(key.getBytes());
        SecretKeySpec aes = new SecretKeySpec(encode, 0, encode.length, "AES");
        return aes;
    }

    //解析
    public static Claims parseToken(String token) {
        Claims body = Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();
        return body;
    }

    //解析重载
    public static <T> T parseToken(String token, Class<T> clazz) {
        Claims body = Jwts.parser()
                .setSigningKey(encodeSecret(JWT_KEY))
                .parseClaimsJws(token)
                .getBody();

        return JSON.parseObject(body.getSubject(), clazz);
    }

    public static <T> String refreshToken(String inToken, Class<T> clazz) {
        try {
            JwtUtil.parseToken(inToken);
        } catch (ExpiredJwtException e) {
            Claims claims = e.getClaims();
            T object = JSON.parseObject(claims.getSubject(), clazz);
            //判断时间是否超过某个值
            //过期时间
            Integer createTime = (Integer) claims.get("exp");
            //当前时间
            long time = new Date().getTime();
            Integer currentTime = (int) (time / 1000);
            //判断是否过期时间小于某一个值
            if (currentTime - createTime <= Refresh_Token_Time) {
                //过期时间小于一天  刷新token
                String token = JwtUtil.createToken(object);
                return token;
            }
        } catch (Exception e) {
            return null;
        }
        //token未过期 放回原来的token
        return inToken;
    }
}


